import React, {Component} from 'react';
import {Map, Marker, InfoWindow, MapvLayer, PointLabel, Polyline,NavigationControl } from 'react-bmap';
import BMap from 'BMap';
import {Button, Card, Col, Icon, DatePicker, Modal, Radio, message,Progress ,Select} from "antd";


import moment from "moment";
import CustomMarker from "./CustomMarker";
import StartMarker from './StartMarker'
import PlayMarker from './PlayMarker'
import CurrentMarker from './CurrentMarker'

import {STAY, TRAIL} from "../../config/const";
import styles from "../Map/index.less";
import {wgs84tobd09} from "../../utils/coordtransform";
import CustomClusterMarker from "../Map/CustomClusterMarker";
import StayMarker from "./StayMarker";
import MarkerClusterer from "../../utils/MarkerClusterer";
import {computeColor} from "../../utils/utils";

moment.locale('zh-cn');
const RadioButton = Radio.Button;
const RadioGroup = Radio.Group;
const { Option } = Select;



class BasicMap extends Component {
    constructor(props) {
        super(props);
        this.state = {
            center: {lng: 115.402544, lat: 39.928216},
            zoom: 6,
            playPosition:{lng: 155.402544, lat: 30.928216},
            isPlay:false,
            playIdx:0,
            playSpeed:'快',

            isShowShareModal: false,
            isShareDone: false,
            confirmLoading: false,
            shareRsp: null,
            today: moment(),
            // prevStatus:false,
            // nextStatus:true,
            lineData: {
                day: '',
                data: [],
                device_id: ''
            },
        };
        this.Map = React.createRef();

        this.zoom = 6
    }

    /**
     * 这使用来
     */
    static getDerivedStateFromProps(props, state) {
        const marks = props.marks;
        const length = marks.length;
        const newState = {};
        if (length > 0) {
            Object.assign(newState, {center: marks[length - 1].xy, zoom: 6});
        }
        // newState  最后一个经纬度信息
        return newState;
    }

    handleWheelAction = () => {
        this.zoom = this.Map.current && this.Map.current.map.getZoom();
        this.props.setEventHandler({
            infoWindowPosition: null,
            infoWindowText: '',
        })
        // this.forceUpdate()
    };
    markersEventHandler = (current_device) => {
        //把点的信息到信息框
        const {infoWindowHandler} = this.props;
        return { //这里的click
            click(e) {
                let point = null;
                if (e.target && e.target.point) {
                    point = e.target.point
                } else {
                    point = {lng: current_device.lng, lat: current_device.lat}
                }
                infoWindowHandler(point, current_device);
            }
        }
    };

    test = (item) => {
        const {infoWindowTest} = this.props;
        return { //这里的click
            click(e) {
                let point = null;
                if (e.target && e.target.point) {
                    point = e.target.point
                } else {
                    point = {lng: item.lng, lat: item.lat}
                }
                infoWindowTest(point, item);
            }
        }
    }
    myStayPoint = (item) => {
        const {infoWindow} = this.props;
        return { //这里的click
            click(e) {
                let point = null;
                if (e.target && e.target.point) {
                    point = e.target.point
                } else {
                    point = {lng: item.lng, lat: item.lat}
                }
                infoWindow(point, item);
            }
        }
    }
    /**
     * 弹框的点击事件
     */
    infoWindowEventsHandler = () => {//这是信息弹框的绑定函数-----！！！！！！！！！
        const self = this;
        return {
            open(e) {
                if (!self.bubbleContentDom) {
                    const bubbleContentDom
                        = self.bubbleContentDom
                        = document.querySelector('.BMap_bubble_content');
                    bubbleContentDom.addEventListener('click', self.bubbleContentHandler);
                }
            }
        }
    };

    bubbleContentHandler = (e) => {//点击停留轨迹触发的事件
        const target = e.target;
        const type = target.className;
        if (target && target.className) {
            this.props.getCurrentLine();//获取单条线的数据
            this.props.getStayPoints(this.props.checkedKeys);//获取停留点数据
            const {setEventHandler} = this.props;

            if ([STAY, TRAIL].includes(type)) {//点击停留触发的事件-----当存在位置时显示信息框
                setEventHandler({
                    isTrail: true,
                    infoWindowPosition: null,
                })
            }
        }
    };

    getRandomPointColor = (idx) => {
        var colors = {
            "204": '#9cbc3f',
            "205": 'purple',
            "206": '#008080',
            "207": '#9cbc3f',
            "208": '#d67d2c',
            "209": '#008080',
            "210": '#627a9d',
            "211": '#735144',
            "212": '#ba5694',
            "213": '#1885a1',
            "214": '#d67d2c',
            "215": '#505aa5',
            "216": '#9cbc3f',
            "217": '#1885a1',
            "218": 'yellow',
            "219": 'blue',
            "220": 'red',
            "1871164491": 'red',
            "1871165693": 'blue',
            "1871165694": "red",
            "1871165695": "red",
            "1871165696": "red",
            "1871165697": "rgba(250,50,231,1)",
            "1871165698": 'red',
            "1871165699": "green",
            "1893058630": "#008080",
            "1893058631": "red",
            "1893058632": "#ffba37",
            "1893058633": "blue",
            "1893058634": "red",
            "1893058635": "#ba5694",
            "1893058636": "#735144",
            "1893058637": "#c19581",
            "1893058638": "#627a9d",
            "1893058639": '#576b43',
            "1893058640": '#d67d2c',
            "1893058641": "#1885a1",
            "1893058642": "#ba5694",
            "1893058643": "#735144",
            "1893058644": "#c19581",
            "1893058645": "#627a9d",
            "1893058646": "#576b43",
            "1893058647": "#66bdaa",
            "1893058648": "#d67d2c",
            "1893058649": "#505aa5",
            "1893072156": "#9cbc3f",
            "1893072157": "rgba(250,50,231,1)",
            "1893072158": "#008080",
            "1893072159": "yellow",
            "1893072160": "#ffba37",
            "1893072161": "green",
            "1893072162": 'blue',
            "1893072163": 'red',
        };
        return colors[idx]
    };
    handlerTrailData = (trails) => {
        var lineColor = this.props.getRandomLineColor(trails.device_id);
        var pointColor = this.getRandomPointColor(trails.device_id);
        const ptData = [];
        const plData = [];
        // let lastSpeed = 0;
        let lastXy = null;
        trails.data.forEach((item, idx) => {
            if (!item) return;
            var a = new wgs84tobd09();
            // const speed = item.speed / 1e3;
            const xy = a.convert_xy(item.lat_lng[1], item.lat_lng[0]);
            // const xy = [item.lat_lng[1], item.lat_lng[0]];
            const pt = {
                "geometry": {
                    "type": "Point",
                    "time": item.time,
                    "device_id": trails.device_id,
                    "coordinates": xy
                },
                // "fillStyle": computeColor(speed),
                "fillStyle": pointColor,//这里是点的颜色
                "count": idx,
            };
            ptData.push(pt);

            if (idx > 0) {
                const pl = {
                    "geometry": {
                        "type": 'LineString',
                        "device_id": trails.device_id,
                        "coordinates": [
                            lastXy, xy
                        ]
                    },
                    // "strokeStyle": computeColor((lastSpeed + speed) / 2),
                    "strokeStyle": lineColor,//这里是线的颜色
                    "count": idx,
                };
                plData.push(pl);
            }
            // lastSpeed = speed;
            lastXy = xy;
        });
        const startPt = ptData[0];
        const endPt = ptData[ptData.length - 1];

        const centerPt = ptData[parseInt(ptData.length / 2)];
        // console.log(ptData.length,parseInt(ptData.length/2))
        let startXY = {};
        let endXY = {};
        let centerXY = {};
        if (startPt) {
            startXY = {
                lng: startPt.geometry.coordinates[0],
                lat: startPt.geometry.coordinates[1],
                device_id: startPt.geometry.device_id,
                time: startPt.geometry.time
            };
            endXY = {
                lng: endPt.geometry.coordinates[0],
                lat: endPt.geometry.coordinates[1],
                device_id: startPt.geometry.device_id,
                time: endPt.geometry.time
            };
            centerXY = {
                lng: centerPt.geometry.coordinates[0],
                lat: centerPt.geometry.coordinates[1],
                device_id: startPt.geometry.device_id,
                time: centerPt.geometry.time
            }

        }

        return [ptData, plData, startXY, endXY, centerXY];
    };


    /**
     * 时间选择
     */
    getDate = (date, dateString) => {
        // console.log(date, dateString);
        this.setState({
            today: date
        });
        this.props.getCurrentLine();
    };

    disabledDate = (current) => {
        var day = moment("2019-09-02");
        return current > moment().endOf('day') || current < day;
    };
    
    /**
     * 线上点的点击事件
     */
    handleTrailPointClick = (e) => {
        if (e && e.geometry) {
            let lng = e.geometry.coordinates[0];
            let lat = e.geometry.coordinates[1];
            // [lng, lat] = gcj02tobd09(lng, lat);
            var Current_time = moment(parseInt(e.geometry.time)).format('YYYY-MM-DD HH:mm:ss');
            const xy = {lng, lat};
            // todo fix
            const text = `
             <dl>
              <dt >设备名称:</dt>
                <dd>${this.props.idToName(e.geometry.device_id)}</dd>
              <dt >设备ID:</dt>
                <dd>${e.geometry.device_id}</dd>
              <dt>时间:</dt>
                <dd>${Current_time}</dd>
              <dt>坐标:</dt>
                <dd>${lng}, ${lat}</dd>
            </dl>
          `;
            this.props.setEventHandler({
                infoWindowPosition: xy,
                infoWindowText: text,
                cur_device: [e.geometry.device_id]
            })
        }
    };

    handleStartClick = (item) => {
        const {infoWindowTest} = this.props;
        return {
            click(e) {
                let point = null;
                if (e.target && e.target.point) {
                    point = e.target.point
                } else {
                    point = {lng: item.lng, lat: item.lat}
                }
                if (item) {
                    var info = {
                        device_id: item.device_id,
                        time: moment(new Date(item.time)).format('YYYY-MM-DD HH:mm:ss')
                    };
                    infoWindowTest(point, info)
                }
            }
        }
    }

    handleMarkerCluster(marks, points) {
        if (marks.length < 1) return [];
        if (this.Map.current) {
            const map = this.Map.current.map;
            const newMarkers = marks.map((item, idx) => {
                const pt = new BMap.Point(item.xy.lng, item.xy.lat);
                const mk = new BMap.Marker(pt);
                mk.info = points[idx];
                return mk;
            });
            const markerClusterer = new MarkerClusterer(map, {markers: newMarkers});
            return markerClusterer.getClusters();
        }

    }


    render() {
        const {zoom} = this.state;
        const that = this;
        const {
            cur_device,
            infoWindowPosition,
            infoWindowText,
            deviceListVisible,
            onDeviceListVisible,
            isTrail,
            getCurrentPoint,
            checkedKeys,
            nextStatus,
            prevStatus,
            lineData, lines,
            prevDay,
            nextDay,
            getDate, today, currentPoint,
            center,
            stayLists,playSpeed,playIdx,isPlay,playPosition,playRail,progress,handleSpeedChange,prevPoint,nextPoint,//停留点
            marks, points, setEventHandler,handleRequestFullScreen,isFullScreen,
        } = this.props;
        const [ptData, plData, startXY, endXY, centerXY] = that.handlerTrailData(lineData);

        function getClusterMarkers(clusters) {
            if (clusters)
                return clusters.map((cluster, idx) => {
                        const len = cluster._markers.length;
                        if (len === 1) {
                            const info = cluster._markers[0].info;
                            return (<CustomMarker key={idx}
                                                  events={that.markersEventHandler(info)}
                                                  position={cluster._center}/>
                            )
                        }
                        const deviceList = [];
                        const clusterInfo = cluster._markers.map((mk, idx) => {
                            const device_id = mk.info.device_id;
                            deviceList.push('' + device_id);
                            return React.createElement('p', {key: idx}, `${device_id}`)
                        });

                        return (<CustomClusterMarker key={idx} events={{
                                click() {
                                    setEventHandler({checkedKeys: deviceList,})
                                }
                            }}
                                                     clusterInfo={React.createElement('div', null, clusterInfo)}
                                                     index={cluster._markers.length}
                                                     position={cluster._center}/>
                        )
                    }
                )
        }

        const ptOptions = {
            // shadowColor: 'rgba(255, 50, 50, 1)',
            // globalCompositeOperation: 'lighter',
            shadowBlur: 0,
            methods: {
                click: this.handleTrailPointClick,
            },
            size: 5,
            draw: 'simple'
        };
        const plOptions = {
            // globalCompositeOperation: 'lighter',
            methods: {
                click: this.handleTrailClick,
            },
            color: 'red',
            lineWidth: 3.8,
            outlineColor: 'red',
            draw: 'simple',
        };

        /**
         * 二维数组的遍历：停留点是二维
         */
        var arr = [];
        stayLists.map((item) => {
            item.map((ele) => {
                arr.push(ele)
            })
        });
        const clusters = that.handleMarkerCluster(marks, points);
        var current_device=cur_device.map(item=>that.props.idToName(item));

        var timeFormatter='0000-00-00';
        if(lineData.data[playIdx]){
            timeFormatter=moment(lineData.data[playIdx].time).format('YYYY-MM-DD HH:mm:ss');
        }
        return (
            <Card
                bodyStyle={{padding: '0'}}
                title={!!isTrail ?
                    <React.Fragment>
                        <Button type="primary" onClick={getCurrentPoint}>当前设备: {current_device.join(',')}
                            <Icon type="close"/>
                        </Button>
                        {/*<Button onClick={this.handleClickShareMap}>创建分享链接</Button>*/}
                    </React.Fragment> : '地图'}
                bordered={false}
                extra={
                    <div className={styles.salesExtraWrap} style={{textAlign: "center",}}>
                        <Button onClick={playRail} style={{display:isTrail?'inline-block':'none'}}>{isPlay ? '暂停' : '开始'}播放</Button>&nbsp;&nbsp;
                        <Button onClick={onDeviceListVisible}>{deviceListVisible ? '关闭' : '显示'}设备列表</Button>&nbsp;&nbsp;
                        <Button type="primary" onClick={prevDay} disabled={prevStatus}>前一天</Button>
                        <DatePicker
                            onChange={getDate}
                            placeholder={'请选择日期'}
                            allowClear={false}
                            defaultValue={moment()}
                            value={today}
                            disabledDate={this.disabledDate}
                        />
                        <Button type="primary" onClick={nextDay} disabled={nextStatus}>后一天</Button>
                        &nbsp;&nbsp;
                        <Button onClick={handleRequestFullScreen}>{isFullScreen ? '退出' : '进入'}全屏模式</Button>
                    </div>
                }
            >
                <div>
                    <Map ref={this.Map} center={center} zoom={zoom}
                         style={{height: 'calc(100vh - 250px)'}}
                         enableScrollWheelZoom={true}
                         enableMapClick={false}
                         events={{
                             zoomend: this.handleWheelAction,
                             dragend: this.handleWheelAction
                         }}
                    >
                        {
                            <div style={{'height':'50px',display:isTrail?'block':'none'}}>
                                {/*<div style={{'background':'red','height':'10px','border-radius':'15px'}}>*/}
                                    <Progress percent={progress}  />
                                {/*</div>*/}
                                <div style={{'background':'white','height':'40px','lineHeight':'40px','textAlign':'center'}} >
                                    <span style={{'float':'left'}}>{timeFormatter}</span>
                                    <span style={{'cursor':'pointer'}}>
                                        <Icon type="fast-backward" style={{fontSize: '20px'}} onClick={prevPoint}/>
                                        <Icon
                                            type={isPlay?'pause-circle':'play-circle'}
                                            theme="twoTone"
                                            twoToneColor="#eb2f96"
                                            style={{'width':'40px',fontSize: '27px', color: '#08c'}}
                                            onClick={playRail}
                                        />
                                        <Icon type="fast-forward" style={{fontSize: '20px'}} onClick={nextPoint}/>
                                    </span>
                                    <Radio.Group value={playSpeed} onChange={handleSpeedChange} style={{'float':'right'}}>
                                        <Radio.Button value="30000">快</Radio.Button>
                                        <Radio.Button value="10000">中</Radio.Button>
                                        <Radio.Button value="5000">慢</Radio.Button>
                                    </Radio.Group>
                                </div>
                            </div>
                        }

                        {/*<StartMarker*/}
                        {/*    position={{lng:110,lat:30}}*/}
                        {/*    type={'end'}*/}
                        {/*/>*/}

                        {
                            (isTrail)&&<CurrentMarker
                                position={playPosition}
                            />
                        }

                        {
                            !isTrail || this.zoom > 13 ? (currentPoint&&currentPoint.map(function (item, index) {
                                return (
                                    !isTrail && (<CustomMarker
                                        key={item.demo_id}
                                        position={{lng: item.lng, lat: item.lat}}
                                        events={that.markersEventHandler(item)}
                                        index={index}
                                        title={that.props.idToName(item.demo_id)}
                                    >
                                    </CustomMarker>)
                                )
                            })) : null
                        }
                        {
                            arr.length > 0 && arr.map(function (item, index) {
                                return (
                                    isTrail && (<PlayMarker
                                            key={index}
                                            position={{lng: item.lng, lat: item.lat}}
                                            events={that.myStayPoint(item)}
                                            index={index}
                                        />
                                    )
                                )
                            })
                        }
                        {
                            checkedKeys.length > 0 && lines.map(function (item, index) {
                                const [ptData, plData, startXY, endXY] = that.handlerTrailData(item);
                                return (
                                    isTrail && (Object.keys(startXY).length > 0 &&
                                        <StartMarker
                                            position={startXY}
                                            icon="start"
                                            key={index}
                                            device_id={item.device_id}
                                            title={item.device_id}
                                            events={that.handleStartClick(startXY)}
                                        />

                                    )
                                )
                            })
                        }
                        {
                            checkedKeys.length > 0 ? lines.map(function (item, index) {
                                const [ptData, plData, startXY, endXY] = that.handlerTrailData(item);
                                return (
                                    isTrail && (Object.keys(startXY).length > 0 && <StartMarker
                                        position={endXY}
                                        icon="end"
                                        type={'end'}
                                        key={index}
                                        title={item.device_id}
                                        events={that.handleStartClick(endXY)}
                                    />)
                                )
                            }) : null
                        }
                        {
                            checkedKeys.length > 0 ? lines.map(function (item, index) {
                                const [ptData, plData, startXY, endXY] = that.handlerTrailData(item);
                                return (
                                    isTrail && <MapvLayer data={plData} options={plOptions} key={index}/>
                                )
                            }) : null
                        }
                        {
                            checkedKeys.length > 0 ? lines.map(function (item, index) {
                                const [ptData, plData, startXY, endXY] = that.handlerTrailData(item);
                                return (
                                    isTrail && that.zoom > 7 ?
                                        <MapvLayer data={ptData} options={ptOptions} key={index}/> : null
                                )
                            }) : null
                        }
                        {
                            (infoWindowPosition && (
                                <InfoWindow
                                    position={infoWindowPosition}
                                    events={this.infoWindowEventsHandler()}
                                    text={infoWindowText}
                                    width={300} height={0}/>
                            ))
                        }
                        {
                            isTrail && (Object.keys(startXY).length > 0 && <StartMarker
                                position={startXY}
                                icon="start"
                                title={cur_device}
                                events={that.handleStartClick(startXY)}
                            />)
                        }
                        {
                            isTrail && (Object.keys(startXY).length > 0 && <StartMarker
                                position={endXY}
                                // icon="end"
                                type={'end'}
                                title={cur_device}
                                events={that.handleStartClick(endXY)}
                            />)
                        }
                        {
                            (isTrail && this.zoom > 8) ? <MapvLayer data={ptData} options={ptOptions}/> : null
                        }
                        {
                            isTrail && <MapvLayer data={plData} options={plOptions}/>
                        }
                        {
                            <NavigationControl />
                        }
                    </Map>
                </div>
            </Card>
        );
    }
}

export default BasicMap;